package com.example.war;

import javax.microedition.khronos.opengles.GL10;

import android.R.integer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;

public class OldFire {
    
    private Context mContext;
    private long mLastDrawTime;
    private int mCurrentIndex = 0;
    private static final int NUM_FRAMES = 40;
    private Quad[] mFrames = new Quad[NUM_FRAMES];
    private static final int INTERVAL_TIME = 50;
    private static final int RES_IDS[] = {
        R.raw.fire1, R.raw.fire2, R.raw.fire3, R.raw.fire4,
        R.raw.fire5, R.raw.fire6, R.raw.fire7, R.raw.fire8,
        R.raw.fire9, R.raw.fire10, R.raw.fire11, R.raw.fire12,
        R.raw.fire13, R.raw.fire14, R.raw.fire15, R.raw.fire16,
        R.raw.fire17, R.raw.fire18, R.raw.fire19, R.raw.fire20,
        R.raw.fire21, R.raw.fire22, R.raw.fire23, R.raw.fire24,
        R.raw.fire25, R.raw.fire26, R.raw.fire27, R.raw.fire28,
        R.raw.fire29, R.raw.fire30, R.raw.fire31, R.raw.fire32,
        R.raw.fire33, R.raw.fire34, R.raw.fire35, R.raw.fire36,
        R.raw.fire37, R.raw.fire38, R.raw.fire39, R.raw.fire40,
    };
    
    private int mIntervalAdjust = 0;
    private Point mScrSize;

    public OldFire(Context context, GL10 gl) {
        mContext = context;
        for (int i = 0; i < mFrames.length; i++) {
            mFrames[i] = new Quad(false);
            initQuad(gl, mFrames[i], RES_IDS[i]);
        }
        mScrSize = Utils.getScreenSize(context);
    }

    private void initQuad(GL10 gl, Quad quad, int resId) {
        Bitmap bitmap = Utils.loadRawImage(mContext.getResources(), resId);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        quad.setSize(width, height);
        quad.setTexture(gl, bitmap, false);
        bitmap.recycle();
    }

    public void draw(GL10 gl) {
        long currentTime = System.currentTimeMillis();
        
        if (mLastDrawTime == 0 || currentTime - mLastDrawTime > (INTERVAL_TIME + mIntervalAdjust)) {
            mCurrentIndex++;
            if (mCurrentIndex >= NUM_FRAMES) {
                mCurrentIndex = 1;
                mIntervalAdjust = 0;
            } else {
                mIntervalAdjust = 0;
            }
            mLastDrawTime = System.currentTimeMillis();
        }
        gl.glPushMatrix();
        Quad quad = mFrames[mCurrentIndex];
        float yPos = -(mScrSize.y - quad.mHeight)/2.0f;
        quad.draw(gl, 0, 0, yPos, 0, true);
        gl.glPopMatrix();
    }
    
    public void clean(GL10 gl) {
        for (Quad quad : mFrames) {
            quad.deleteTexture(gl);
        }
    }
}
